<template>
  <el-dialog
    v-model="showDialog"
    destroy-on-close
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    :width="width"
    :before-close="handleBeforeClose"
    :top="tops"
    :draggable="draggable"
    :class="customClass"
    :show-close="showClose"
    :align-center="alignCenter"
  >
    <slot></slot>
    <template #footer v-if="hideIsFooter">
      <slot name="footer">
        <div class="dialog-footer">
          <el-button @click="handleClose">{{ cancelButtonText }}</el-button>
          <el-button type="primary" :loading="confirmLoading" @click.stop="handleSubmit" @keyup.enter="keyDown">
            {{ confirmButtonText }}
          </el-button>
        </div>
      </slot>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from "vue";
interface Props {
  width?: number; // 弹窗宽度
  title?: string; // 弹窗标题
  hideIsFooter?: boolean; // 判断是否显示#footer
  tops?: string; // 	dialog CSS 中的 margin-top 值，默认为 15vh
  cancelButtonText?: string; // 取消按钮文本
  confirmButtonText?: string; // 确定按钮文本
  confirmLoading?: boolean; // 确认按钮加载状态
  draggable?: boolean; // 是否可拖拽
  customClass?: string; // 自定义类名
  showClose?: boolean; // 是否显示关闭icon按钮
  alignCenter?: boolean; // 弹窗是否居中对齐
  enableEnterConfirm?: boolean; // 回车提交事件
}
const {
  width = 750,
  hideIsFooter = true,
  tops = "15vh",
  cancelButtonText = "取消",
  confirmButtonText = "确定",
  confirmLoading = false,
  draggable = false,
  customClass = "",
  showClose = true,
  alignCenter = false,
  enableEnterConfirm = true,
} = defineProps<Props>();
// 弹窗显隐
const showDialog = ref<boolean>(false);
const emits = defineEmits<{
  submit: [_row: any];
  close: [boolean];
}>();
// 确认
const handleSubmit = () => {
  emits("submit");
};
// 取消
const handleClose = (): void => {
  closePopupsDialog();
  emits("close", false);
};
// 关闭前的回调
const handleBeforeClose = (done: () => void) => {
  emits("close", false);
  window.removeEventListener("keydown", keyDown, false);
  done();
};
// 关闭
const closePopupsDialog = (): void => {
  showDialog.value = false;
  window.removeEventListener("keydown", keyDown, false);
};
// 打开
const openPopupsDialog = (): void => {
  showDialog.value = true;
  nextTick(() => {
    window.addEventListener("keydown", keyDown);
  });
};
// 键盘回车事件
const keyDown = (e: any) => {
  if (e.keyCode === 13 && enableEnterConfirm) {
    e.preventDefault();
    handleSubmit();
  }
};
defineExpose({
  closePopupsDialog,
  openPopupsDialog,
});
</script>
